package com.example.Lezedata.dataManager;
/*用户管理*/
import android.content.SharedPreferences;
import android.os.UserManager;
import android.preference.PreferenceManager;

import androidx.lifecycle.Observer;

import com.example.Lezedata.GBApplication;
import com.example.Lezedata.dataModel.UserDataModel;
import com.example.Lezedata.dataModel.UserInfoManager;
import com.example.Lezedata.net.GBError;
import com.example.Lezedata.net.GBNetRequest;
import com.example.Lezedata.net.ServerResponseObserver;
import com.example.Lezedata.ui.tabBar.GBTabBarVc;
import com.example.Lezedata.util.GBSaveData;
import com.example.Lezedata.util.GBUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import bid.Bid;
import common.Common;
import io.grpc.Server;

import static android.content.Context.MODE_PRIVATE;

public class GBUserManager  {
    public static GBUserManager manager;
    // token
    public String token = getLocalToken();
    // 用户信息
    public Bid.UserInfo userInfo;
    // 是否设置支付密码
    public Boolean hasPIN;
    /// 余额
    public long balance;

    public void setLoginData(Bid.LoginResponse data){
        if (data == null){
            return;
        }
        balance = data.getBalance();
        userInfo = data.getUserInfo();
        token = data.getToken();
        hasPIN = data.getExistTransPw();
        saveLoginInfo();
    }

    public static String TOKEN_KEY = "token";

    public static String getUserId(){
        return instance().userInfo.getUserId();
    }

    public static Bid.UserInfo userInfo(){
        return instance().userInfo;
    }

    public static GBUserManager instance() {
        if (manager == null){
            manager = new GBUserManager();
            manager.initData();
        }
        return manager;
    }

    public GBUserManager(){
    }

    void initData(){
        initLocalUserData();
        addLoginStatueListener();
    }

    void addLoginStatueListener(){
        LoginManager manager = LoginManager.instance();
        manager.loginStatus.observeForever(new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if (LoginManager.LoginStatus_exit.intValue() == integer.intValue()){
                    exit();
                }
            }
        });
    }

    // 用户退出登录
    void exit(){
        clearUserInfo();
    }

    // 清空用户信息
    void clearUserInfo(){
        token = "";
        userInfo = Bid.UserInfo.newBuilder()
                .setUserId("")
                .build();
        balance = 0;
        hasPIN = false;
        setUserData();
        clearLocalToken();
    }

    void saveLoginInfo(){
        //存储数据时选用对应类型的方法
        GBSaveData.setData(TOKEN_KEY,token);
        setUserData();
    }

    void setUserData() {
        UserDataModel model = new UserDataModel();
        model.balance = balance;
        model.userId = userInfo.getUserId();
        model.hasPIN = hasPIN;
        Gson gson = new Gson();
        String js = gson.toJson(model);
        GBSaveData.setData("UserData",js);
    }

    UserDataModel getUserData(){
        String js = GBSaveData.getData("UserData");
        Gson gson = new Gson();
        UserDataModel model = gson.fromJson(js,UserDataModel.class);
        if (model == null){
            model = new UserDataModel();
            model.userId = "";
            model.balance = 0;
            model.hasPIN = false;
        }
        return model;
    }

    static String getLocalToken() {
        return GBSaveData.getData(TOKEN_KEY);
    }

    static void clearLocalToken(){
        GBSaveData.setData(TOKEN_KEY,"");
    }

    void initLocalUserData() {
        UserDataModel model = getUserData();
        userInfo = Bid.UserInfo.newBuilder()
                .setUserId(model.userId)
                .build();
        balance = model.balance;
        hasPIN = model.hasPIN;
        autoLogin();
    }

    void autoLogin(){
        if (GBUtil.stringIsEmpty(token)){
            return;
        }
        LoginManager.instance().setLoginStatus(LoginManager.LoginStatus_login);
        GBNetRequest.stubUser().autoLogin(Bid.AutoLoginRequest.newBuilder().build(), ServerResponseObserver.observer(new ServerResponseObserver.requestListener<Bid.LoginResponse>() {
            @Override
            public void complete(Bid.LoginResponse value, GBError error) {
                if (error == null){
                    setLoginData(value);
                }else {
                    LoginManager.instance().setLoginStatus(LoginManager.LoginStatus_failure);
                    clearUserInfo();
                }
            }
        }));
    }
}